'use client'

import { useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { FunnelChart, Funnel, LabelList, ResponsiveContainer, Tooltip } from 'recharts'

type TimeRange = 'day' | 'week' | 'month' | 'custom'
type MetricType = 'tangzhuang' | 'movie' | 'hanfu' | 'aivideo'

interface FunnelData {
  name: string
  value: number
  percent?: number
  uv?: number
}

const STEPS = ['点击模块', '确认风格', '生成结果']
const METRICS = [
  { value: 'tangzhuang', label: '唐装写真' },
  { value: 'movie', label: '热门影视剧妆造' },
  { value: 'hanfu', label: '制式汉服' },
  { value: 'aivideo', label: 'AI唐风视频' },
]

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

const calculatePercent = (current: number, previous: number) => {
  if (previous === 0) return 0
  return Math.round((current / previous) * 100)
}

export default function UserBehavior() {
  const [timeRange, setTimeRange] = useState<TimeRange>('day')
  const [selectedMetric, setSelectedMetric] = useState<MetricType>('tangzhuang')
  const [funnelData, setFunnelData] = useState<FunnelData[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      // 设置当前日期为2025-01-14用于测试
      const testDate = '2025-01-14'
      const response = await fetch(
        `/api/user-behavior/funnel?timeRange=custom&startDate=${testDate}&endDate=${testDate}&metrics[]=${selectedMetric}`,
        {
          headers: {
            'Accept': 'application/json',
          }
        }
      )
      
      if (!response.ok) {
        throw new Error('获取数据失败')
      }
      
      const data = await response.json()
      console.log('API Response:', data) // 调试用

      // Transform API data to funnel chart format
      if (data[selectedMetric]) {
        const { pv, uv } = data[selectedMetric]
        console.log('Processing metric:', selectedMetric, { pv, uv }) // 调试用
        
        const newFunnelData = STEPS.map((step, index) => {
          const value = pv[index] || 0
          const prevValue = index > 0 ? pv[index - 1] || 1 : value
          const percent = index === 0 ? 100 : calculatePercent(value, prevValue)
          
          return {
            name: step,
            value,
            percent,
            uv: uv[index] || 0
          }
        })
        console.log('Transformed data:', newFunnelData) // 调试用
        setFunnelData(newFunnelData)
      }
    } catch (error) {
      console.error('Error fetching funnel data:', error)
      setError(error instanceof Error ? error.message : '获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [timeRange, selectedMetric])

  const CustomTooltip = ({ active, payload }: any) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload
      return (
        <div className="bg-white p-3 shadow-lg rounded-lg border">
          <p className="font-medium">{data.name}</p>
          <p className="text-sm">访问量(PV): {formatNumber(data.value)}</p>
          <p className="text-sm">独立访客(UV): {formatNumber(data.uv || 0)}</p>
          {data.percent !== undefined && (
            <p className="text-sm">转化率: {data.percent}%</p>
          )}
        </div>
      )
    }
    return null
  }

  const CustomLabel = ({ x, y, width, height, value, name, percent, uv }: any) => {
    return (
      <g>
        <text x={x + width + 10} y={y + height / 2} fill="#000" textAnchor="start">
          <tspan x={x + width + 10} dy="-12">{name}</tspan>
          <tspan x={x + width + 10} dy="20">
            PV: {formatNumber(value)}
          </tspan>
          <tspan x={x + width + 10} dy="20">
            UV: {formatNumber(uv || 0)}
          </tspan>
          {percent !== undefined && percent !== 100 && (
            <tspan x={x + width + 10} dy="20" fill="#666">
              转化率: {percent}%
            </tspan>
          )}
        </text>
      </g>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <Select value={timeRange} onValueChange={(value: TimeRange) => setTimeRange(value)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="选择日期" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="day">今天</SelectItem>
            <SelectItem value="week">本周</SelectItem>
            <SelectItem value="month">本月</SelectItem>
          </SelectContent>
        </Select>
        <Select value={selectedMetric} onValueChange={(value: MetricType) => setSelectedMetric(value)}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="选择指标" />
          </SelectTrigger>
          <SelectContent>
            {METRICS.map(metric => (
              <SelectItem key={metric.value} value={metric.value}>
                {metric.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Card>
        <CardHeader>
          <CardTitle>漏斗转化分析</CardTitle>
        </CardHeader>
        <CardContent>
          {error ? (
            <div className="h-[300px] flex items-center justify-center text-red-500">
              {error}
            </div>
          ) : loading ? (
            <div className="h-[300px] flex items-center justify-center">
              加载中...
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={400}>
              <FunnelChart>
                <Tooltip content={<CustomTooltip />} />
                <Funnel
                  dataKey="value"
                  data={funnelData}
                  isAnimationActive
                  width={400}
                >
                  <LabelList
                    position="right"
                    fill="#000"
                    stroke="none"
                    content={CustomLabel}
                  />
                </Funnel>
              </FunnelChart>
            </ResponsiveContainer>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

